var express = require('express')
    , path = require('path')
    , app = express()
    , server = require('http').createServer(app);
var io = require('socket.io')(server);

app.set('port', 3002);

var redis = require('redis'),
    RDS_PORT = 6379,        //端口号
    RDS_HOST = '192.168.1.201',    //服务器IP
    RDS_OPTS = {},            //设置项
    client = redis.createClient(RDS_PORT,RDS_HOST,RDS_OPTS);
var sub = redis.createClient(RDS_PORT,RDS_HOST,RDS_OPTS),
    pub = redis.createClient(RDS_PORT,RDS_HOST,RDS_OPTS);

var clientSetKey = "nodeClientSet";
var nodeJSNodeKey = "";

client.on('ready',function(res){
    console.log('ready');
});
client.on('end',function(err){
    console.log('end');
});

client.on('connect',function(){
    client.get('NodeNum', function(err,value){
        if (value == null){
            client.set("NodeNum","1");
            nodeJSNodeKey = "Node1";
        }else{
            var nodeStr = ""+(new Number(value)+1);
            client.set("NodeNum",nodeStr);
            nodeJSNodeKey = "Node"+nodeStr;
        }
        sub.subscribe(nodeJSNodeKey);
        console.info("client register on redis "+nodeJSNodeKey);
    });
});

sub.on("message", function (channel, message) {
    console.log("sub channel " + channel + ": " + message);
    //接收消息，消息格式：fromKey::toKey::msg
    var messageArray = message.split("::");
    var fromKey = messageArray[0]
    var toKey = messageArray[1];
    var toMsg = messageArray[2];
    var toSocket;
    if(toKey in users){
        toSocket = users[toKey];
        toSocket.emit("message",{from:fromKey,msg:toMsg})
    }
});

// angular启动页
app.get('/', function (req, res) {
    res.sendfile('app/index.html');
});

// /user 节点接受 PUT 请求
app.get('/user', function (req, res) {
    res.send('Got a PUT request at /user');
});

server.listen(app.get('port'), function () {
    console.log('Express server listening on port ' + app.get('port'));
});

//在线用户
var users = new Array();

io.on('connection', function(socket){
    console.log('client:'+socket.client.id+' connected');

    //监听用户发布聊天内容
    socket.on('register', function(){
        var registerKey = generateRegisterKey();
        console.log("register, key is "+registerKey);
        users[registerKey] = socket;
        //向客户端发送注册成功的消息
        socket.emit('registerAck', registerKey);

        //Redis中添加客户端
        client.set(registerKey,nodeJSNodeKey);
        client.sadd(clientSetKey, registerKey);

        refreshClientList(registerKey,socket)
    });

    //监听用户发布聊天内容
    socket.on('clientList', function(from){
        refreshClientList(from,socket)
    });

    function refreshClientList(from,socket){
        var clientKeysList = new Array();
        //从redis中读取
        client.multi()
            .smembers(clientSetKey)
            .exec(function (err, replies) {
                replies.forEach(function (reply, index) {
                    clientKeysList = reply.toString().split(",");
                    socket.emit('clientListAck', clientKeysList);
                });
            });
    }

    //监听用户发布聊天内容
    socket.on('message', function(from,toKey,msg){
        //放到Redis中，根据toKey查询Node节点，然后直接放入节点队列。
        client.get(toKey, function(err,value){
            console.info(value);
            var toNode = value;
            pub.publish(toNode, ""+from+"::"+toKey+"::"+msg);
        });

    });

    socket.on('disconnect', function () {
        //remove Redis中的节点。
        console.info("client disconnected");
        for (var index in users){
            var user = users[index];
            if (user != undefined && socket.client.id == user.client.id){
                client.del(index);
                //this.split(index, 1);
            }
        }
    });
});



var range=function(start,end) {
    var array=[];
    for(var i=start;i<end;++i) array.push(i);
    return array;
};

var generateRegisterKey=function() {
    var registerKey = range(0,6).map(function(x){
        return Math.floor(Math.random()*10);
    }).join('');
    return registerKey;
};